package com.examination.client.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.examination.client.domian.dto.UserTokenDTO;
import com.examination.client.entity.UserInfo;

import java.util.*;

/**
 * @author: XiaoDong
 * @date: 2021-10-23 20:04
 * @description:
 */

public class JwtTokenUtil {


    /**
     * 密钥
     */
    private static final String C_TOKEN_SECRET = "CMhnESyF6mwdBAPa66DeIm2sEwFbSxYjA";
    private static final String B_TOKEN_SECRET = "DII9tgosSbgGiwoGEdCoCmtvIjxDI958";


    /**
     * 7天
     */
    private static final long TIME_OUT = 7 * 24 * 60 * 60 *1000;


    /**
     * 生成toekn
     *
     * @param userTokenDTO
     * @return
     */
    public static String createToken(UserTokenDTO userTokenDTO) {
        try {
            System.out.println(userTokenDTO);
            Date expiration_time = new Date(System.currentTimeMillis() + TIME_OUT);
            Algorithm algorithm = Algorithm.HMAC256(C_TOKEN_SECRET);
            Map<String, Object> headerMap = new HashMap<>(2);
            headerMap.put("type", "JWT");
            headerMap.put("alg", "HS256");
            return JWT.create()
                    .withHeader(headerMap)
                    .withClaim("userId", userTokenDTO.getUserId())
                    .withClaim("userName",userTokenDTO.getUserName())
                    .withClaim("userType", userTokenDTO.getUserType())
                    .withClaim("siteId",userTokenDTO.getSiteId())
                    .withClaim("nextSiteId",userTokenDTO.getNextSiteId())
                    .withClaim("parentSiteId",userTokenDTO.getParentSiteId())
                    .withExpiresAt(expiration_time).sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }




    /**
     * 验证Token
     * @param token
     * @return
     */
    public static boolean verifyToken(String token) {

        try {
            Algorithm algorithm = Algorithm.HMAC256(C_TOKEN_SECRET);
            JWTVerifier jwtVerifier = JWT.require(algorithm).build();
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            return false;
        }

        return true;
    }


    /**
     * 计算过期时间
     * @return
     */
    private static Map<String, Date> calculateExpiredIssues() {
        Map<String, Date> map = new HashMap<>();
        Calendar calendar = Calendar.getInstance();
        Date now = calendar.getTime();
        calendar.add(Calendar.SECOND, (int)TIME_OUT);
        // 当前时间
        map.put("now", now);
        // 过期时间
        map.put("expiredTime", calendar.getTime());
        return map;
    }

    /**
     * 获取自定义数据
     * @param token
     * @return
     */
    public static Optional<Map<String, Claim>> getClaims(String token) {
        DecodedJWT decodedJWT;

        // 指定算法
        Algorithm algorithm = Algorithm.HMAC256(C_TOKEN_SECRET);
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();

        try {
            decodedJWT = jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            return Optional.empty();
        }

        return Optional.of(decodedJWT.getClaims());
    }

    /**
     * 获取自定义数据
     * @param platformType
     * @return
     */
    public static String getSecret(Integer  platformType) {
        if(platformType==1){
            return C_TOKEN_SECRET;
        }
        if(platformType==2){
            return B_TOKEN_SECRET;
        }
        return null;
    }

}
